package br.com.lp3.livraria.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.lp3.livraria.util.HibernateUtil;

public abstract class GenericoDao<Tipo> {

	private static EntityManager entityManager;

	public Tipo buscarPorId(Long id) {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		return (Tipo) entityManager.find(getGenericType(), id);
	}

	public void salvar(Tipo entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.persist(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public void deletar(Tipo entity) {

		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.remove(entity);
			entityManager.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		}
	}

	public void alterar(Tipo entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		}
	}

	public List<Tipo> buscartodos() {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		Query query = entityManager.createQuery("FROM "
				+ getGenericType().getSimpleName());
		return query.getResultList();
	}

	private Class getGenericType() {
		return (Class) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
	}
}